package com.edu.netty.netty;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.edu.netty.entity.MessageEntity;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.Date;
import java.util.Random;

/**
 * <p>
 * netty客户端
 * </p>
 *
 * @author jpge
 * @since 2024-03-29
 */
public class Client {

    private String ip;
    private int port;

    public void connect(String ip, int port) throws InterruptedException {
        // 定义线程池
        EventLoopGroup worker = new NioEventLoopGroup();

        try {
            // 定义启动引导类
            Bootstrap bootstrap = new Bootstrap();

            // 设置启动类属性
            bootstrap.group(worker)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new ClientHandle(getMsg("ME000001")));
                        }
                    });

            // 启动客户端
            ChannelFuture channelFuture = bootstrap.connect(ip, port).sync();
            channelFuture.channel().closeFuture();
        } finally {

        }
    }

    public static void main(String[] args) throws InterruptedException {
        new Client().connect("127.0.0.1", 10010);
    }

    /**
     * 产生模拟报文数据
     */
    private String getMsg(String meterCode) {
        MessageEntity entity = new MessageEntity();
        entity.setMetercode(meterCode);

        // 设置随机温度
        entity.setTem(getRandom(-100, 100));

        // 设置锁机湿度
        entity.setHum(getRandom(0, 150));

        // 设置随机状态
        entity.setState(getRandom(0, 100) % 3);

        // 设置 经纬度
        entity.setLon("117.17");
        entity.setLat("31.52");

        // 设置当前时间
        entity.setCurtime(DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN));

        return entity.toString();
    }

    /**
     * 获得俩个数字间随机数字
     */
    private int getRandom(int min, int max) {
        Random random = new Random();
        return random.nextInt(max) % (max - min + 1) + min;
    }

}
